package pers.jl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import pers.jl.common.MyException;
import pers.jl.entity.Category;
import pers.jl.entity.Dish;
import pers.jl.entity.Setmeal;
import pers.jl.mapper.CategoryMapper;
import pers.jl.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import pers.jl.service.IDishService;
import pers.jl.service.ISetmealService;

/**
 * <p>
 * 菜品及套餐分类 服务实现类
 * </p>
 *
 * @author luge
 * @since 2023-04-22
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    // 注入菜品分类service
    @Autowired
    private IDishService dishService;

    // 注入套餐分类service
    @Autowired
    private ISetmealService setmealService;

    // 判断该分类是否关联其他菜品，如果有其他菜品，就不能删除，反之可以删除
    @Override
    public boolean remove(Long id) {

        // 是否有关联菜品
        LambdaQueryWrapper<Dish> lambdaDishQueryWrapper = new LambdaQueryWrapper<>();
        // 判断菜品分类id是否相等
        lambdaDishQueryWrapper.eq(Dish::getCategoryId,id);
        int count1 = dishService.count(lambdaDishQueryWrapper);
        if (count1 > 0) {
            // 含有关联菜品，不能删除，抛出自定义的异常
            throw new MyException("该菜品含有其他关联食物，无法删除！");
        }

        // 是否有关联套餐
        LambdaQueryWrapper<Setmeal> lambdaSetmealQueryWrapper = new LambdaQueryWrapper<>();
        // 判断套餐分类id是否相等
        lambdaSetmealQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(lambdaSetmealQueryWrapper);
        if (count2 > 0) {
            // 含有关联套餐，不能删除，抛出自定义的异常
            throw new MyException("该套餐含有其他关联菜品，无法删除！");
        }

        // 没有关联，直接删除
        return super.removeById(id);
    }
}
